package service.network;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import materials.network.NetworkInterface;

/**
 * Represents a Service to Save or Load Neuronal Networks
 * 
 * @author User
 * 
 */
public class NetworkFilesystemService {

	/**
	 * Saves a Neuronal Network to a specific File
	 * 
	 * @param f
	 *            - The File
	 * @param currentNetwork
	 *            - The Network which should be saved
	 */
	public void saveNetwork(File f, NetworkInterface currentNetwork) {
		try {
			OutputStream os = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(currentNetwork);
			oos.flush();
			oos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Load a NeuronalNetwork from the FileSystem
	 * 
	 * @param f
	 *            - File
	 * @return Neuronal Network
	 */
	public NetworkInterface loadNetwork(File f) {
		assert f != null : "Vorbedingung verletzt: f != null";
		try {
			InputStream is = new FileInputStream(f);
			ObjectInputStream ois = new ObjectInputStream(is);
			Object o = ois.readObject();
			if (o instanceof NetworkInterface) {
				ois.close();
				return (NetworkInterface) o;
			} else {
				ois.close();
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
